package com.dycloud.project.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.dycloud.project.constant.Constants;
import com.dycloud.project.domain.Meetings;
import com.dycloud.project.domain.SysUser;
import com.dycloud.project.dto.MeetingReceiptDTO;
import com.dycloud.project.enums.ReviewStatusEnum;
import com.dycloud.project.enums.ServiceTypeEnum;
import com.dycloud.project.exception.ServiceException;
import com.dycloud.project.mapper.MeetingsMapper;
import com.dycloud.project.request.ReviewMeetingRequest;
import com.dycloud.project.security.LoginUser;
import com.dycloud.project.service.IMeetingReceiptService;
import com.dycloud.project.service.IMeetingsService;
import com.dycloud.project.service.ISysUserService;
import com.dycloud.project.utils.DateUtils;
import com.dycloud.project.utils.SecurityUtils;
import com.dycloud.project.vo.MeetingPageVO;
import com.dycloud.project.vo.PushTrendItemVo;
import com.dycloud.project.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : renhang
 * @description MeetingsServiceImpl
 * @date : 2025-07-03 14:04
 **/
@Service
public class MeetingsServiceImpl implements IMeetingsService {

    @Autowired
    private MeetingsMapper meetingsMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    @Lazy
    private IMeetingReceiptService meetingReceiptService;

    /**
     * 查询会议
     *
     * @param id 会议主键
     * @return 会议
     */
    @Override
    public Meetings selectMeetingsById(Long id) {
        return meetingsMapper.selectMeetingsById(id);
    }


    /**
     * 查询会议列表
     *
     * @param meetings 会议
     * @return 会议
     */
    @Override
    public TableDataInfo selectMeetingsList(Meetings meetings, Integer source) {
        // 租户隔离,admin可以看所有的
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (SecurityUtils.isCommonUser()) {
            meetings.setPublishId(loginUser.getUserId());
        }
        List<Meetings> meetingsList = meetingsMapper.selectMeetingsList(meetings);
        if (CollUtil.isEmpty(meetingsList)) {
            return TableDataInfo.build(meetingsList, meetingsList);
        }

        List<MeetingPageVO> vos = meetingToPageVo(meetingsList);

        if (Objects.equals(source, ServiceTypeEnum.MINI_PROGRAM.getCode())) {
            List<Long> meetingIds = vos.stream().map(MeetingPageVO::getId).toList();
            // 用户id+ 当前登录用户id
            List<MeetingReceiptDTO> meetingReceiptDTOList = meetingReceiptService.queryUserIsWrite(meetingIds, loginUser.getUserId());
            Map<Long, MeetingReceiptDTO> map = meetingReceiptDTOList.stream().collect(Collectors.toMap(MeetingReceiptDTO::getMeetingId, v -> v));
            vos.forEach(item -> {
                if (Objects.nonNull(map.get(item.getId()))) {
                    item.setIsWriteReceipt(1);
                }
            });
        }
        return TableDataInfo.build(vos, meetingsList);
    }

    @Override
    public List<MeetingPageVO> meetingToPageVo(List<Meetings> meetingsList) {
        Set<Long> publishIds = meetingsList.stream().map(Meetings::getPublishId).collect(Collectors.toSet());
        publishIds.addAll(meetingsList.stream().map(Meetings::getAuditorId).collect(Collectors.toSet()));
        Map<Long, SysUser> sysUserMap = sysUserService.getUserInfoMap(publishIds);

        return meetingsList.stream().map(item -> {
            MeetingPageVO meetingPageVO = BeanUtil.copyProperties(item, MeetingPageVO.class);
            meetingPageVO.setNickName(Objects.nonNull(sysUserMap.get(item.getPublishId())) ? sysUserMap.get(item.getPublishId()).getNickName() : null);
            if (Objects.nonNull(item.getAuditorId())) {
                meetingPageVO.setAuditorName(sysUserMap.get(item.getAuditorId()).getNickName());
            }
            return meetingPageVO;
        }).toList();
    }

    /**
     * 新增会议
     *
     * @param meetings 会议
     * @return 结果
     */
    @Override
    public int insertMeetings(Meetings meetings) {
        // 管理员创建的不需要审核
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            meetings.setStatus(ReviewStatusEnum.PUBLISHED.getCode());
            meetings.setAuditorId(SecurityUtils.getUserId());
            meetings.setAuditTime(DateUtils.getNowDate());
        }
        meetings.setCreateTime(DateUtils.getNowDate());
        meetings.setPublishId(SecurityUtils.getUserId());
        meetings.setUpdateTime(DateUtils.getNowDate());
        return meetingsMapper.insertMeetings(meetings);
    }

    /**
     * 修改会议
     *
     * @param meetings 会议
     * @return 结果
     */
    @Override
    public int updateMeetings(Meetings meetings) {
        checkIsReview(meetings.getId());
        meetings.setUpdateTime(DateUtils.getNowDate());
        return meetingsMapper.updateMeetings(meetings);
    }

    /**
     * 批量删除会议
     *
     * @param ids 需要删除的会议主键
     * @return 结果
     */
    @Override
    public int deleteMeetingsByIds(Long[] ids) {
        for (Long id : ids) {
            checkIsReview(id);
        }
        return meetingsMapper.deleteMeetingsByIds(ids);
    }

    /**
     * 删除会议信息
     *
     * @param id 会议主键
     * @return 结果
     */
    @Override
    public int deleteMeetingsById(Long id) {
        return meetingsMapper.deleteMeetingsById(id);
    }

    @Override
    public void review(ReviewMeetingRequest request) {
        request.getIds().forEach(id -> {
            Meetings meetings = meetingsMapper.selectMeetingsById(id);
            if (Objects.isNull(meetings)) {
                throw new RuntimeException("id:" + id + "的会议不存在");
            }
        });

        List<Meetings> list = request.getIds().stream().map(e -> {
            Meetings meetings = new Meetings();
            meetings.setId(e);
            meetings.setAuditorId(SecurityUtils.getUserId());
            meetings.setStatus(request.getStatus());
            meetings.setAuditRemark(request.getAuditRemark());
            meetings.setUpdateTime(DateUtils.getNowDate());
            meetings.setAuditTime(DateUtils.getNowDate());
            return meetings;
        }).toList();

        meetingsMapper.updateListMeetings(list);
    }

    @Override
    public List<Meetings> selectMeetingByIds(List<Long> ids) {
        return meetingsMapper.selectMeetingByIds(ids);
    }

    private void checkIsReview(Long id) {
        Meetings meetings = meetingsMapper.selectMeetingsById(id);
        if (Objects.isNull(meetings)) {
            throw new ServiceException("会议不存在");
        }
        if (Objects.equals(meetings.getIsDel(), Constants.ONE)) {
            throw new ServiceException("会议已删除");
        }
        if (Objects.equals(meetings.getStatus(), Constants.ONE)) {
            throw new ServiceException("已经进行中的会议不能修改");
        }
    }

    @Override
    public int selectCount(Long userId) {
        return meetingsMapper.selectCount(userId);
    }

    @Override
    public List<PushTrendItemVo> selectPushTrend(Long userId) {
        return meetingsMapper.selectPushTrend(userId);
    }
}